<?php

class BaiduAction extends CommonAction {

    private $account;
    private $password;
    private $cookie_jar;
    private $bid;

    public function baidu() {
        $keywords = iconv('utf-8', 'gb2312', $this->_request('keywords'));
        $act = $this->_request('act');
        if ($act == 'add') {
            $this->authUser();
            if (($_SESSION['user']['user_advance'] == 1 && $_SESSION['user']['user_advance_time'] > time()) || $this->getAddTimesAll() > 0) {
                $this->_addKeywords($keywords);
                if (!($_SESSION['user']['user_advance'] == 1 && $_SESSION['user']['user_advance_time'] > time())) {
                    $this->updateAddtimes();
                }
                $Keywords = M('Keywords');
                $data = array(
                    'user_id' => $_SESSION['user']['user_id'],
                    'keywords' => $this->_post('keywords'),
                    'add_time' => time()
                );
                $Keywords->add($data);
                redirect('/Baidu/success');
            } else {
                $this->assign('waitSecond', 5);
                $this->error('添加次数为0，每天可以免费添加1次。升级为高级会员无限次数添加。', '/Ucenter/advance');
            }
        } else if ($act == 'search') {
            $url = 'http://index.baidu.com/main/word.php?word=' . urlencode($keywords);
            redirect($url);
        }
    }

    public function success() {
        $this->display();
    }

    private function _addKeywords($keywords) {
        $this->_init();
        $this->_login();
        $this->_add($keywords);
        $this->_delete();
    }

    private function _init() {
        $this->account = iconv('utf-8', 'gb2312', '2009年6月21号');
        $this->password = 'wodeyuan';
        $this->cookie_jar = dirname($_SERVER["SCRIPT_FILENAME"]) . '/cookie.txt';
    }

    private function _login() {
        
        //获取登录token
        $return = $this->curl_get_contents('https://passport.baidu.com/v2/api/?getapi&class=login&tpl=nx&tangram=false', $this->cookie_jar);
         preg_match('/bdPass.api.params.login_token=\'(.*)\';/', $return, $token);
         $token = $token[1];
         //登录
         $data = 'charset=UTF-8&token='.$token.'&isPhone=false&index=0&u=http://index.baidu.com/&safeflg=0&staticpage=https://passport.baidu.com/v2Jump.html&loginType=1&tpl=nx&callback=parent.bdPass.api.login._postCallback&username='.$this->account.'&password='.$this->password;
         $this->curl_get_contents('https://passport.baidu.com/v2/api/?login', $this->cookie_jar, 'post', $data);
        /*
          $url				= 'https://passport.baidu.com/?login';
          $fields_post 	= 'tpl_ok=&next_target=&tpl=&skip_ok=&aid=&need_pay=&need_coin=&pay_method=';
          $fields_post	.='&u=./&return_method=get&more_param=&return_type=&psp_tt=0&password=';
          $fields_post 	.= $this->password;
          $fields_post 	.= '&safeflg=0&isphone=false&username='.$this->account.'&verifycode=';
          // 登录部份
          $curl_session = curl_init();
          curl_setopt($curl_session, CURLOPT_URL, $url);
          curl_setopt($curl_session, CURLOPT_SSL_VERIFYPEER, 0);
          curl_setopt($curl_session, CURLOPT_SSL_VERIFYHOST, 1);
          curl_setopt($curl_session, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
          curl_setopt($curl_session, CURLOPT_POST, 1);
          curl_setopt($curl_session, CURLOPT_POSTFIELDS,$fields_post);
          curl_setopt($curl_session, CURLOPT_COOKIEJAR, $this->cookie_jar);
          curl_setopt($curl_session, CURLOPT_COOKIEFILE, $this->cookie_jar);
          curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, 1);
          $temp = curl_exec($curl_session);
          if ($temp == NULL) {
          echo "Error:
          ";
          echo curl_errno($curl_session) . " - " . curl_error($curl_session) . "
          ";
          }
          curl_close($curl_session);
         */
           /*
        $this->doHttpPost("http://hm.baidu.com/h.js?8c869b543955d43e496c2efee5b55823", "", "");
        $preLoginData = $this->doHttpPost('https://passport.baidu.com/v2/api/?getapi&class=login&tpl=qing', "", "");
        preg_match('/bdPass.api.params.login_token=\'(.*)\';/', $preLoginData, $login_token);
        $post_data = "charset=UTF-8&codestring=&token=" . $login_token[1] . "&isPhone=false&index=0&u=http%3A%2F%2Fhi.baidu.com%2Fgo%2Flogin%3Ffrom_page%3D0%26from_mod%3D101&safeflag=0&staticpage=http%3A%2F%2Fhi.baidu.com%2Fcom%2Fshow%2Fproxy%3Ffun%3Dcallback.login.submited&loginType=1&tpl=qing&username=" . $this->account . "&password=" . $this->password . "&verifycode=&mem_pass=on";
        $LoginData = $this->doHttpPost("https://passport.baidu.com/v2/api/?login", $post_data, "");

        preg_match('/encodeURI\(\'(.*)\'/', $LoginData, $proxy_url);
        $data = $this->doHttpPost($proxy_url[1], "", "");
        $data = $this->doHttpPost("http://hi.baidu.com/go/login", $post_data, "");
        preg_match('/window.qBdsToken=\"([0-9a-z]+)\"/', $data, $token);
        $this->bdstoken = $token[1];
         */
    }

    private function _add($keywords) {
        $url = 'http://index.baidu.com/main/myindex.php';
        $curl_session = curl_init();
        curl_setopt($curl_session, CURLOPT_URL, $url);
        curl_setopt($curl_session, CURLOPT_HEADER, 0);
        curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl_session, CURLOPT_COOKIEFILE, $this->cookie_jar);
        //curl_setopt($curl_session, CURLOPT_POST, 1);
        //curl_setopt($curl_session, CURLOPT_POSTFIELDS, $data);
        $temp = curl_exec($curl_session);
        curl_close($curl_session);
        //$pattern = '/bid=([\w]+)\"/';
        //preg_match_all($pattern, $temp, $matches);
        //$this->bid = $data['bid'] = $matches[1][0];
        $this->bid = $data['bid'] = 21781;
        $url = "http://index.baidu.com/tools/add_word_to_board.php?u=http%3A%2F%2Findex.baidu.com%2Fmain%2Fmyboard.php%3Fbid%3D" . $data['bid'];
        $data['word'] = $keywords;
        $curl_session = curl_init();
        curl_setopt($curl_session, CURLOPT_URL, $url);
        curl_setopt($curl_session, CURLOPT_HEADER, 0);
        curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl_session, CURLOPT_COOKIEFILE, $this->cookie_jar);
        curl_setopt($curl_session, CURLOPT_POST, 1);
        curl_setopt($curl_session, CURLOPT_POSTFIELDS, $data);
        $temp = curl_exec($curl_session);
        curl_close($curl_session);
    }

    private function _delete() {
        $url = "http://index.baidu.com/main/myboard.php?bid=" . $this->bid;
        $curl_session = curl_init();
        curl_setopt($curl_session, CURLOPT_URL, $url);
        curl_setopt($curl_session, CURLOPT_HEADER, 0);
        curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl_session, CURLOPT_COOKIEFILE, $this->cookie_jar);
        $temp = curl_exec($curl_session);
        curl_close($curl_session);

        $pattern = '/tools\/delete_word_from_board\\.php\\?bwid=(.*?)&u=http/is';
        preg_match_all($pattern, $temp, $arr);

        $url = 'http://index.baidu.com/tools/delete_word_from_board.php?bwid=' . $arr[1][3] . '&u=http%3A%2F%2Findex.baidu.com%2Fmain%2Fmyboard.php%3Fbid%3D' . $this->bid;

        $curl_session = curl_init();
        curl_setopt($curl_session, CURLOPT_URL, $url);
        curl_setopt($curl_session, CURLOPT_HEADER, 0);
        curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl_session, CURLOPT_COOKIEFILE, $this->cookie_jar);
        $temp = curl_exec($curl_session);
        curl_close($curl_session);
    }

    /*
    private function doHttpPost($url, $post_data, $referef) {
        $mcurl = curl_init();
        curl_setopt($mcurl, CURLOPT_URL, $url);

        if ($post_data != "") {
            curl_setopt($mcurl, CURLOPT_POST, 1);
            curl_setopt($mcurl, CURLOPT_POSTFIELDS, $post_data);
        }

        if ($referef != "") {
            curl_setopt($mcurl, CURLOPT_REFERER, $referef);
        }

        curl_setopt($mcurl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($mcurl, CURLOPT_SSL_VERIFYPEER, 0);
        //curl_setopt($mcurl, CURLOPT_HEADER, 1);
        curl_setopt($mcurl, CURLOPT_HEADER, 0);
        curl_setopt($mcurl, CURLOPT_HTTPHEADER, array('Accept-Language: zh-cn', 'Connection: Keep-Alive', 'Cache-Control: no-cache'));
        curl_setopt($mcurl, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.2; WOW64; Trident/6.0; .NET4.0E; .NET4.0C; .NET CLR 3.5.30729; .NET CLR 2.0.50727; .NET CLR 3.0.30729)");
        curl_setopt($mcurl, CURLOPT_FOLLOWLOCATION, TRUE);
        curl_setopt($mcurl, CURLOPT_MAXREDIRS, 4);
        curl_setopt($mcurl, CURLOPT_AUTOREFERER, TRUE);

        curl_setopt($mcurl, CURLOPT_RETURNTRANSFER, TRUE); //设置成非0/true，则获得的内容不会被输出
        curl_setopt($mcurl, CURLOPT_COOKIEJAR, $this->cookie_jar);
        curl_setopt($mcurl, CURLOPT_COOKIEFILE, $this->cookie_jar);

        $data = curl_exec($mcurl);
        if (curl_errno($mcurl) > 0) {
            exit("CURL ERROR:$url " . curl_error($mcurl));
        }
        curl_close($mcurl);
        return $data;
    }
     * 
     
     */

    private function curl_get_contents($url, $cookie_jar = '', $type = 'get', $data = '') {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);    //启用时会将头文件的信息作为数据流输出
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);    //关闭验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
        
        if ($cookie_jar){
            curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_jar);
            curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_jar);
        }
        if ($type != 'get'){
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        $return = curl_exec($ch);
        curl_close($ch);
        return $return;
    }

}